﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using System.Data;
using System.Data.OleDb;

using Fif.text;

namespace Fif.wss
{
    public class Search : IDisposable
    {
        private const string ConnectionString   = "Provider=Search.CollatorDSO;Extended Properties=\"Application=Windows\"";

        private const string QueryTemplate = "SELECT "
            + "System.ItemName"
            + ", System.ItemPathDisplay" 
            + ", System.Search.Rank"
            + ", System.ItemUrl" 
            + " FROM SystemIndex WHERE scope='file:{0}' and (FREETEXT('{1}', {3}) OR FREETEXT('{2}'))"; // add ', LCID' to specify locale

        private OleDbConnection _connection;

        public Search()
        {
            _connection = new OleDbConnection(ConnectionString);
        }

        public IEnumerable<FileInfo> FindInFiles(string text, string path, string lang)
        {
            var query = BuildQuery(text, path, lang);
            using (var cmd = new OleDbCommand(query))
            {                
                cmd.Connection = _connection;
                if (ConnectionState.Open != _connection.State)
                {
                    _connection.Open();
                }

                using (var reader = cmd.ExecuteReader())
                {
                    while(reader.Read())
                    {                        
                        yield return new FileInfo { 
                            Name = reader.GetString(0),
                            Path = reader.GetString(1),
                            Rank = reader.GetInt32(2),
                            Url = reader.GetString(3)
                        };                         
                    }
                }
            }
        }

        public void Close()
        {
            if (null != _connection)
            {
                _connection.Close();
                _connection = null;
            }            
        }

        public void Dispose()
        {
            Close();
        }

        private static string BuildQuery(string text, string path, string lang)
        {            
            var uglyText = Helper.UnicodeToUglycode(text, lang);
            var unicode =  string.Format(QueryTemplate, path, text, uglyText, Helper.GetLcid(lang));            
            return unicode;
        }
    }
}
